package com.ls.lserp.modules.produce.service;


import com.ls.lserp.common.service.CrudService;
import com.ls.lserp.common.utils.DateUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.dbaccess.Entity.ProductionItemEntity;
import com.ls.lserp.modules.common.entity.Material;
import com.ls.lserp.modules.order.dao.OrderDao;
import com.ls.lserp.modules.order.entity.Order;
import com.ls.lserp.modules.order.entity.StyleOptionEntity;
import com.ls.lserp.modules.produce.dao.CustomizationQualityDao;
import com.ls.lserp.modules.produce.entity.CustomizationQualityEntity;
import com.ls.lserp.modules.produce.entity.ProduceLicense;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.sys.utils.UserUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = false)
public class CustomizationQualityService extends CrudService<CustomizationQualityDao,CustomizationQualityEntity>{

	@Autowired
    private CustomizationQualityDao customizationQualityDao ;
	
	@Autowired
    private OrderDao orderDao ;
	
	/**
     * 获取品控标准信息
     * @param 
     * @return
     */
    public List<StyleOptionEntity> findQualityControl(){

        return customizationQualityDao.findQualityControl();
    }
    /**
     * 获取订单基本信息
     * @param 
     * @return
     */
    public Order getOrderInfo(String orderCd,String operatingId) throws Exception{
    	Order order = customizationQualityDao.getOrderInfo(orderCd,operatingId);
    	String uploadPath = "";
    	List<StyleOptionEntity> cList = null;
    	//获取质检信息（1为自带面料）
    	if ("1".equals(order.getMaterialSource())) {
    		cList = customizationQualityDao.findStyleControlCustom(order.getOrderNO(),operatingId,order.getMakeShirt());
		}else {
			cList = customizationQualityDao.findStyleControl(order.getOrderNO(),operatingId,order.getMakeShirt());
		}
    	if (cList != null && cList.size()>0) {
    		for (int i = 0; i < cList.size(); i++) {
    			if (ResourcesUtil.getConfig("material_code").indexOf(cList.get(i).getItemValue().trim())>0) {
    				if (cList.get(i).getOptionValue().indexOf("/")>0) {
    					uploadPath = customizationQualityDao.getMaterialInfo(cList.get(i).getOptionValue().split("/")[0].trim());
    					if (uploadPath != null && !"".equals(uploadPath)) {
    						cList.get(i).setFilePath(uploadPath);
    					}
    				}
    			}
    		}
		}
    	order.setStyleOpList(cList);
    	
        return order;
    }
    
    /**
     * 生产号查询量尺01所需数据
     * @param 
     * @return
     */
    public Order getDataOfFit01(String orderCd){
    	
        return customizationQualityDao.getDataOfFit01(orderCd);
    }
    
    /**
     * 获取订单基本信息
     * @param 
     * @return
     */
    public List<Order> findAllList(Order order,Long operatingId){
    	order.setOperatingId(operatingId);
    	List<Order> orders = customizationQualityDao.findAllOrderList(order);
    	for (Order orz:orders) {
    		if (orz!=null) {
    			orz.setStyleOpList(customizationQualityDao.findStyleControl(orz.getStyleNo(),operatingId+"",""));
			}
		}
        return orders;
    }

    /**
     * 查存
     * @param
     * @return
     */
    public String selectOperatingId (String ip){
        return customizationQualityDao.selectOperatingId(ip);
    }
    
    /**
     * 查存
     * @param 
     * @return
     */
    public Order getOrderByNo(String orderCd){

        return customizationQualityDao.getOrderByNo(orderCd);
    }

    /**
	 * 修改检查状态
	 * @param styleOptionEntity
	 */
    @Transactional(readOnly = false)
    public String updateQcCheck(StyleOptionEntity styleOptionEntity) {
        String returnFLg;
        // 如果质检结果中不包括通过或未通过
        if (styleOptionEntity.getQcCheck ()!=null && (styleOptionEntity.getQcCheck ().indexOf ("1") == -1
                && styleOptionEntity.getQcCheck ().indexOf ("2") == -1)) {
            returnFLg = "noChange";
        } else {
			if (styleOptionEntity.getQcCheck ()!=null && (styleOptionEntity.getQcCheck ().indexOf ("1") != -1
					&& styleOptionEntity.getQcCheck ().indexOf ("2") == -1)) {
				returnFLg = "changeAll_OK";
			} else {
				returnFLg = "change_Fail";
			}
            String[] qcCheck = styleOptionEntity.getQcCheck ().split (",");
            String[] qcId = styleOptionEntity.getStrQcId ().split (",");
            int okCount = 0;
            int fLaseCount = 0;
            for (int i = 0; i < qcCheck.length; i++) {
                if ("2".equals (qcCheck[i])) {
                    if (styleOptionEntity.getOrderStatus () == null) {
                        styleOptionEntity.setOrderStatus ("QUALITY_STATUS-QC_02");
                    }
                    //获取质检相关信息
                    StyleOptionEntity qualityInfo = customizationQualityDao.getQualityInfo(qcId[i]);
                    qualityInfo.setQcOperatingId(styleOptionEntity.getItemId());
                    qualityInfo.preInsert();
                    //插入质检未通过信息
                    customizationQualityDao.insertDetailInfo(qualityInfo);
                    fLaseCount++;
                } else if ("1".equals (qcCheck[i])) {
                    okCount++;
                }
                // 更新数据
                styleOptionEntity.preUpdate ();
                customizationQualityDao.updateQcCheck (qcCheck[i], styleOptionEntity.getUpdateBy ().getId (), qcId[i]);
            }
            // 全部通过的时候，状态为全通过
            if (okCount > 0 && fLaseCount == 0) {
                styleOptionEntity.setOrderStatus ("QUALITY_STATUS-QC_01");
                saveOrderStatus (styleOptionEntity);
            } else if (fLaseCount > 0) {
            	styleOptionEntity.setOrderStatus ("QUALITY_STATUS-QC_02");
                saveOrderStatus (styleOptionEntity);
            }
        }
        return returnFLg;
    }
    /**
	 * 插入工时表
	 * @param styleOptionEntity
	 */
    @Transactional(readOnly = false)
    public void saveProItem(StyleOptionEntity styleOptionEntity) {
    	// 更新数据
    	String operatingStatus = customizationQualityDao.getOperatingStatus(styleOptionEntity);
    	if (ResourcesUtil.getConfig("quatity_status_20").equals(styleOptionEntity.getOrderStatus()) 
    			|| ResourcesUtil.getConfig("quatity_status_30").equals(styleOptionEntity.getOrderStatus())) {
    		operatingStatus = ResourcesUtil.getConfig("OPERATING_STATUS20");
		}
    	ProductionItemEntity productionItemEntity = new ProductionItemEntity();
    	Long productionId = customizationQualityDao.getProductionId(styleOptionEntity.getOrderID());
    	if (productionId != null) {
    		productionItemEntity.setProductionId(productionId);
    		productionItemEntity.setCreateDateTime(new Date());
    		productionItemEntity.setUpdateDateTime(new Date());
    		productionItemEntity.setCreateUserId(UserUtils.getUser().getId());
    		productionItemEntity.setUpdateUserId(UserUtils.getUser().getId());
    		productionItemEntity.setOrderId(styleOptionEntity.getOrderID());
    		productionItemEntity.setOrderNo(styleOptionEntity.getCustomOrderNO());
    		productionItemEntity.setBarCode(styleOptionEntity.getCustomOrderNO());
    		productionItemEntity.setItemId(Long.parseLong(styleOptionEntity.getItemId()));
    		productionItemEntity.setProcessStatus(operatingStatus);
    		productionItemEntity.setProcessNumber(new BigDecimal(1));
    		orderDao.insertProItem(productionItemEntity);
		}
}
    
    /**
	 * 修改检查状态
	 * @param styleOptionEntity
	 */
    @Transactional(readOnly = false)
    public void saveOrderStatus(StyleOptionEntity styleOptionEntity) {
    	if ("1".equals (styleOptionEntity.getChangeFlg ())) {
			String[] qcCheck = styleOptionEntity.getQcCheck ().split (",");
			String[] qcId = styleOptionEntity.getStrQcId ().split (",");
			for (int i = 0; i < qcCheck.length; i++) {
				// 更新数据
				styleOptionEntity.preUpdate ();
				customizationQualityDao.updateQcCheck (qcCheck[i], styleOptionEntity.getUpdateBy ().getId (), qcId[i]);
			}
		}
    	// 更新数据
    	styleOptionEntity.preUpdate();
    	customizationQualityDao.saveOrderStatus(styleOptionEntity);
    	Order order = orderDao.getOrderQuatityInfo(styleOptionEntity.getOrderID());
    	if (order != null) {
			if (ResourcesUtil.getConfig("quatity_status_20").equals(order.getOrderQuatityStatus34())
					|| ResourcesUtil.getConfig("quatity_status_30").equals(order.getOrderQuatityStatus34())
					|| ResourcesUtil.getConfig("quatity_status_20").equals(order.getOrderQuatityStatus35())
					|| ResourcesUtil.getConfig("quatity_status_30").equals(order.getOrderQuatityStatus35())
					|| ResourcesUtil.getConfig("quatity_status_20").equals(order.getOrderQuatityStatus36())
					|| ResourcesUtil.getConfig("quatity_status_30").equals(order.getOrderQuatityStatus36())
					|| ResourcesUtil.getConfig("quatity_status_20").equals(order.getOrderQuatityStatus37())
					|| ResourcesUtil.getConfig("quatity_status_30").equals(order.getOrderQuatityStatus37())) {
				
				order.setOrderProduceStatusCd(ResourcesUtil.getConfig("production_12"));
				order.preInsert();
				orderDao.updateProduceStatus(order);
			}
		}
    	String operatingStatus = customizationQualityDao.getOperatingStatus(styleOptionEntity);
    	if (!"".equals(operatingStatus) && operatingStatus != null) {
    		//质检通过
	    	if (ResourcesUtil.getConfig("quatity_status_10").equals(styleOptionEntity.getOrderStatus())) {
	    		//如果原工序状态为待返工或返工完成，则工序状态为返工完成
    			if (ResourcesUtil.getConfig("OPERATING_STATUS20").equals(operatingStatus)||ResourcesUtil.getConfig("OPERATING_STATUS30").equals(operatingStatus)) {
    				styleOptionEntity.setOrderStatus(ResourcesUtil.getConfig("OPERATING_STATUS30"));
    			//如果原工序状态为待待加工，则工序状态为完成
    			}else if (ResourcesUtil.getConfig("OPERATING_STATUS00").equals(operatingStatus)) {
    				styleOptionEntity.setOrderStatus(ResourcesUtil.getConfig("OPERATING_STATUS10"));
    			}
    		//质检未通过、质检未通过（严重）
			}else if (ResourcesUtil.getConfig("quatity_status_20").equals(styleOptionEntity.getOrderStatus())
					||ResourcesUtil.getConfig("quatity_status_30").equals(styleOptionEntity.getOrderStatus())) {
				//设置工序状态为待返工
				styleOptionEntity.setOrderStatus(ResourcesUtil.getConfig("OPERATING_STATUS20"));
			//待检测
			}else{
				//设置工序状态为待生产
				styleOptionEntity.setOrderStatus(ResourcesUtil.getConfig("OPERATING_STATUS00"));
			}
	    	customizationQualityDao.saveOperatingStatus(styleOptionEntity);
    	}
    }
    
    /**
     * 修改检查状态
     * @param styleOptionEntity
     */
    @Transactional(readOnly = false)
    public void updateFitQcCheck(StyleOptionEntity styleOptionEntity) {

        // 更新数据
        styleOptionEntity.preUpdate();
        customizationQualityDao.updateFitQcCheck(styleOptionEntity);
    }
    /**
     * 根据条形码取订单code
     * @param barCode
     */
    public String selectBarCode(String barCode){
        String styleNo =customizationQualityDao.selectBarCode (barCode);
        return styleNo;
    }
}
